<?php
namespace app\wechat\controller;

use think\Controller;
use Des3\DES3;
use think\Db;
use think\Session;

class Login extends Controller
{
    static private $err_code = 0;
    // 绑定手机号码页面
    public function index()
    {
        if (session('?login') && session('login') == 1 && session('?member_id')) {
            $this->redirect(url('member/index'));
            return false;
        }
        else {
            return view();
        }
    }

    // 登录
    public function login()
    {
        try{
            $des = new DES3();
            $param = [
                'phone' => $des->encrypt(input('param.phone')),
                'password' => $des->encrypt(input('param.password', '')),
                'code' => input('param.code', ''),
                'type' => input('param.type'),
            ];
            $member = call_interface('login', $param);
            if ($member['code'] == 200) {
                session('member_id', $member['data']['member_id']);
                session('phone', $member['data']['phone']);
                session('login', 1);
            }
            $member['url'] = session('?login_to_page') ? session('?login_to_page') : url('member/index');
            return json($member);

        } catch (\Exception $e) {
            return json(['code' => self::$err_code, 'msg' => $e->getMessage()]);
        }
    }

    // 用户注册页面
    public function register()
    {
        return view();
    }

    // 用户
    public function save_register()
    {
        if(!input('?param.phone') ||
            !input('?param.password') || !input('?param.code')) return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];

        $des = new DES3();
        $param = [
            'phone' => $des->encrypt(input('param.phone')),
            'password' => $des->encrypt(input('param.password')),
            'code' => input('param.code')
        ];
        $parent_phone = input('param.parent_phone', '');
        if (!empty($parent_phone)) {
            $param['parent_phone'] = $des->encrypt($parent_phone);
        }
        $data = call_interface('register', $param);
        if ($data['code'] == 200) {
            if (is_weixin()) {
                //微信端注册成功  使用微头像和昵称
                $this->save_role_info($data['data']['member_id']);
            }
        }
        return json($data);
    }

    // 找回密码页面
    public function reset_psd()
    {
        return view();
    }

    // 找回密码
    public function save_reset_psd()
    {
        if(!input('?param.phone') ||
            !input('?param.password') || !input('?param.code')) return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];

        $des = new DES3();
        $param = [
            'phone' => $des->encrypt(input('param.phone', '')),
            'password' => $des->encrypt(input('param.password', '')),
            'code' => input('param.code', '')
        ];
        $data = call_interface('retrieve_password', $param);
        if ($data['code'] == 200) {
            $data['url'] = url('index');
        }
        return json($data);
    }

    // 获取上级用户姓名
    public function get_referrer() {
        $des = new DES3();
        $param = [
            'phone' => $des->encrypt(input('param.phone'))
        ];
        $data = call_interface('get_referrer', $param);
        return json($data);
    }

    // 检查当前帐号是否有头像和昵称， 没有就使用微信的
    public function save_role_info($member_id) {
        $member_role_info = db('member_role_info')->where('member_id', $member_id)->select();
        foreach ($member_role_info as $v) {
            $member_role_info_data['nickname'] = session('nickname');
            $member_role_info_data['headimgurl'] = session('headimgurl');
            db('member_role_info')->where('id', $v['id'])->update($member_role_info_data);
        }
    }

    // 检查用户是否存在
    public function check_phone() {
        $des = new DES3();
        $param = [
            'phone' => $des->encrypt(input('param.phone'))
        ];
        $data = call_interface('check_phone', $param);
        return json($data);
    }

    // 用户注册页面
    public function band_member()
    {
        if (request()->isPost()) {
            $des = new DES3();
            $param = [
                'phone' => $des->encrypt(input('param.phone')),
                'password' => $des->encrypt(input('param.password', '')),
                'code' => input('param.code', ''),
                'type' => input('param.type'),
            ];
            $member = call_interface('login', $param);
            if ($member['code'] == 200) {
                // 绑定帐号
                model('Member')->save(['openid' => session('openid')], ['id' => $member['data']['member_id']]);
            }
            $member['url'] = session('?login_to_page') ? session('?login_to_page') : url('member/index');
            return json($member);
        } else {
            return view();
        }
    }

    // 微信登录回调地址
    public function wechat_login() {
        $parse_url = parse_url($_SERVER['HTTP_REFERER']);
        if ($_SERVER['HTTP_HOST'] == 'dealers.kaimobangwang.com'){
            $host = 'bg.kaimobangwang.com';
        } else {
            $host = 'mob.mgtvshop.com';
        }
        if ($parse_url['host'] == $host) {
            $param = input('param.');
            if ($param['openid']) {
                // 检查微信是否绑定帐号
                $member = model('member')->where('openid', $param['openid'])->find();
                if ($member) {
                    // 已绑定
                    session('member_id', $member['id']);
                    session('openid', $param['openid']);
                    session('phone', $member['phone']);
                    session('nickname', $param['nickname']);
                    session('headimgurl', $param['headimgurl']);
                    session('login', 1);
                    $this->redirect(url('member/index'));
                } else {
                    session('openid', $param['openid']);
                    // 绑定帐号
                    $this->redirect(url('login/band_member'));
                }
            } else {
                $this->error('微信授权失败！！', url('login/index'));
            }
        } else {
            $url = config('new.interface_url') . 'wechat/wechat_oauth/index';
            exit('<script>window.location.href="'.$url.'"</script>');
        }
    }

    // 检查手机号码是否已经绑定微信号
    public function check_phone_is_band() {
        $phone = input('param.phone', 0);
        $member = model('Member')->get(['phone' => $phone]);
        if ($member['openid']) {
            return json(['code' => 200, 'msg' => '手机号码已绑定微信']);
        }
        return json(['code' => 0, 'msg' => '手机号码未绑定微信']);
    }
}
